package si.unimb.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class ServerListener implements Runnable{

	private ServerSocket server;
	private ServerHost program;
	private List<StreamManager> smList = new ArrayList<StreamManager>();
	private List<Pozicija> pozicije;
	int i;
	
	public ServerListener(int port, ServerHost program){
		try{
			i = 0;
			server = new ServerSocket(port);
			server.setReceiveBufferSize(10);
			this.program = program;
		} catch(IOException e){
			e.printStackTrace();
		}
		new Thread(this).start();
	}
	
	public void run(){
		while(true){
			try{
				Socket socket = server.accept();
				socket.setTcpNoDelay(true);
				StreamManager sm = new StreamManager(socket, this, program, i++);
				program.addText("Client connected!");
				smList.add(sm);
				Thread socketThread = new Thread(sm);
				socketThread.start();
			} catch(Exception e){
				e.printStackTrace();
			}
		}
	}
	
	public void sendAll(byte[] b){
		for(StreamManager sm : smList){
			//Identifikator za tip prenosa podatkov: 0 = sporocilo
			sm.sendByte((byte) 0);	
			//Podatki
			sm.sendString(b);
		}
	}
	
	public void sendAllGameMode(short id, short x, short y){
		for(StreamManager sm : smList){
			//Identifikator za tip prenosa podatkov: 1 = game mode
			sm.sendByte((byte) 1);
			//Podatki
			sm.sendShort(id);
			sm.sendShort(x);
			sm.sendShort(y);
		}
	}
	
	public void removeThread(StreamManager sm){
		smList.remove(sm);
	}
	
	public void dataArrived(short id, short x, short y){
		for(StreamManager sm : smList){
			if(sm.getId() == id){
				pozicije.add(new Pozicija(id, x, y));
				sm.setCitaj(false);
			}
		}
	}
	
	public boolean allClientDataArrived(){
		if(pozicije.size() == smList.size()){
			for(int i = 0; i < smList.size(); i++){
				smList.get(i).setCitaj(true);
				sendAllGameMode(pozicije.get(i).getId(), pozicije.get(i).getX(), pozicije.get(i).getY());
			}
			pozicije.removeAll(pozicije);
			return true;
		}else{
			return false;
		}
	}

	//Preverjanje ce so vsi clienti ze poslali /ready
	public boolean checkReadyClients(){
		int i = 0;
		
		for(StreamManager sm : smList)
			if(sm.isReady())
				i++;
		
		if(smList.size() == i){
			pozicije = new ArrayList<Pozicija>();
			sendClientList();			
			return true;
		}else{
			return false;
		}
	}
	
	
	//Vsem clientom poslje seznam sodelujocih
	public void sendClientList(){
		Random r = new Random();
		
		String list = "/weareready";
		
		for(StreamManager sm : smList){
			sm.setReady(true);
			list += ":" + sm.getNickname() + ":" + sm.getId() + ":" + (r.nextInt(600) + 100) + ":" + (r.nextInt(500) + 100);
		}
		
		sendAll(list.getBytes());
	}
}
